package cn.my.learning.security;

import cn.my.learning.domain.RoleType;
import cn.my.learning.domain.User;
import cn.my.learning.repository.UserRepository;
import cn.my.learning.service.UserServiceImpl;
import cn.my.learning.util.PwdEnAndDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Leo on 2017/5/3.
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider{

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    HttpSession httpSession;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取账号密码和SessionID并写入到数据库，保存登录状态
        String authSessionID = httpSession.getId();
        String userAccount = authentication.getName();
        String userPassword = authentication.getCredentials().toString();
        String remoteAddress = authentication.getDetails().toString().split(": ")[2].split("; ")[0];
        userService.UpdateLoginStatus(userAccount, remoteAddress, authSessionID);

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (validateUser(userAccount, userPassword, grantedAuthorities)) {
            return new UsernamePasswordAuthenticationToken(userAccount, userPassword, grantedAuthorities);
        } else {
            return null;
        }
    }

    /**
     * 验证登录
     * @param userAccount
     * @param userPassword
     * @param grantedAuthorities
     * @return
     */
    private boolean validateUser(String userAccount, String userPassword, List<GrantedAuthority> grantedAuthorities){
        PwdEnAndDecode pwdEnAndDecode = new PwdEnAndDecode();
        User user = userRepository.findUserByAccountAndPassword(userAccount, pwdEnAndDecode.encode(userPassword));
        if(user == null || userAccount == null || userPassword == null){
            return false;
        }
        if(user.getPassword().equals(pwdEnAndDecode.encode(userPassword))){
            grantedAuthorities.add(new SimpleGrantedAuthority(RoleType.USER.name()));
            return true;
        }
        return false;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
